<ui:composition xmlns="http://www.w3.org/1999/xhtml"
                xmlns:ui="http://java.sun.com/jsf/facelets"
                xmlns:h="http://java.sun.com/jsf/html"
                xmlns:f="http://java.sun.com/jsf/core"
                xmlns:p="http://primefaces.prime.com.tr/ui"
                xmlns:vti="http://java.sun.com/jsf/composite/components/vti"
                template="/pages/templates/layout.xhtml">
    <ui:define name="conteudo">
        <script type="text/javascript">
            var conexao = null,
                countInterval = null;
            
            function WebSocketConstruct() {
                var url = "ws://" + document.location.host + "/leilaovirtual/cons?id=" + getParameterByName("id");
                if ("WebSocket" in window) {
                    conexao = new WebSocket(url);
                } else if ("MozWebSocket" in window) {
                    conexao = new WebSocket(url);
                } else {
                    alert("Seu browser não é compatível");
                }

                if (conexao !== undefined) {
                    conexao.onopen = function() {
                        console.log("Conectou com sucesso");
                    };
                    conexao.onclose = function() {
                        console.log("Desconectou com sucesso");
                    };
                    conexao.onerror = function() {
                        console.log("Aconteceu um erro");
                    };
                    conexao.onmessage = function(e) {
                        console.log("Recebeu mensagem");
                        processarMsg(e.data);
                    };
                }
            }
            
            function sendMessage(msg) {
                console.log("Enviar mensagem (" + msg + ")");
                if (conexao !== undefined) {
                    conexao.send(msg);
                }
            }
            
            function ativarComp(comp, val) {
                if (val) {
                    comp.attr("disabled", false).css("display", "inline");
                } else {
                    comp.attr("disabled", true).css("display", "none");
                }
            }

            function processarMsg(texto) {
                var pNum = $("#num");
                var pText = $("#texto");
                pText.html("Segundos");
                var nomeLeilao = $("#nomeLeilao");
                var lanceAtual = $("#lanceAtual");
                var botaoLance = $("#btnEnviar");
                var botaoExtra = $("#btnExtra");
                var spanLance = $("#btnEnviar span");
                
                var arr = texto.split("$");
                if (arr[0] === "JA_GANHOU") {
                    drawTimer(0);
                    pNum.html(0);
                    ativarComp(botaoLance, false);
                    ativarComp(botaoExtra, false);
                    lanceAtual.html(arr[1]);
                } else if (arr[0] === "TEMPO_ESGOTADO") {
                    drawTimer(0);
                    pNum.html(0);
                    ativarComp(botaoLance, false);
                    ativarComp(botaoExtra, false);
                    lanceAtual.html(arr[1]);
                } else if (arr[0] === "COMPRAR_EXTRA") {
                    drawTimer(0);
                    pNum.html(0);
                    ativarComp(botaoLance, false);
                    ativarComp(botaoExtra, (arr[1] !== undefined &amp;&amp; arr[1].indexOf("sucesso") === -1));
                    lanceAtual.html(arr[1]);
                } else if (arr[0] === "NAO_ENCONTRADO") {
                    lanceAtual.html(arr[1]);
                    ativarComp(botaoLance, false);
                } else if (arr[0] === "ENCERRADO") {
                    drawTimer(0);
                    pNum.html(0);
                    nomeLeilao.html(arr[2]);
                    lanceAtual.html(arr[3] + ": R$ " + arr[4] + ",00");
                    ativarComp(botaoLance, false);
                } else if (arr[0] === "VAI_COMECAR") {
                    drawTimer(0);
                    pNum.html(0);
                    nomeLeilao.html(arr[1]);
                    lanceAtual.html(arr[2]);
                    ativarComp(botaoLance, false);
                } else if (arr[0] === "COMECOU") {
                    drawTimer(360);
                    nomeLeilao.html(arr[1]);
                    pNum.html(arr[2]);
                    lanceAtual.html(arr[3]);
                    spanLance.html("Oferecer R$ " + arr[4] + ",00");
                    ativarComp(botaoLance, true);
                } else if (arr[0] === "LANCE") {
                    var segundos = arr[1];
                    pNum.html(segundos);
                    nomeLeilao.html(arr[2]);
                    lanceAtual.html(arr[3] + ": R$ " + arr[4] + ",00");
                    spanLance.html("Oferecer R$ " + arr[5] + ",00");
                    ativarComp(botaoLance, true);
                    var max = arr[6];
                    
                    drawTimer((segundos/(max > 0 ? max : 1)) * 360);
                    if (countInterval !== null) {
                        clearInterval(countInterval);
                    }
                    countInterval = setInterval(function() {
                        if (segundos > 0) {
                            segundos--;
                            var deg = (segundos/(max > 0 ? max : 1)) * 360;
                            pNum.html(segundos);
                            drawTimer(deg);
                        } else {
                            ativarComp(botaoLance, false);
                            sendMessage("ATUALIZAR_GANHADOR");
                            clearInterval(countInterval);
                        }
                    }, 1000);
                }
            }
            
            function drawTimer(deg) {
                var canvas = document.getElementById("canvas"),
                    width = canvas.width,
                    height = canvas.height,
                    ctx = canvas.getContext("2d"),
                    ctxB = canvas.getContext("2d");
                
                var x = width/2,
                    y = height/2,
                    radius = 75,
                    lineWidth = 26,
                    startAngle = 0,
                    endAngle = deg * (Math.PI / 180),
                    counterClockwise = false;

                ctx.clearRect(0, 0, height, width);
                ctx.save();

                ctxB.beginPath();
                ctxB.arc(90, 90, 75, 0, 2 * Math.PI);
                ctxB.lineWidth = lineWidth;
                ctxB.strokeStyle = "#737373";
                ctxB.stroke();
                ctxB.closePath();

                ctx.beginPath();
                ctx.arc(x, y, radius, startAngle, endAngle, counterClockwise);
                ctx.lineWidth = lineWidth-6;
                ctx.strokeStyle = corSel(deg);
                ctx.stroke();
                ctx.closePath();
            }
            
            function corSel(deg) {
                var cor;
                var aux = Math.round(deg);
                if (aux > 240) {
                    cor = "#00DD00";
                } else if (aux > 120) {
                    cor = "#DDDD00";
                } else {
                    cor = "#FF0000";
                }
                return cor;
            }
                
            $(function() {
                WebSocketConstruct();
                var botao = $("#btnEnviar");
                botao.bind("click", function() {
                    sendMessage($("#btnEnviar span").html());
                });
                var botao = $("#btnExtra");
                botao.bind("click", function() {
                    sendMessage("COMPRAR_EXTRA");
                });
            });
        </script>
        <div class="caixaLance">
            <div>
                <div class="ladoEsq">
                    <span id="nomeLeilao"></span>
                    <img src="#{request.contextPath}/resources/images/ingresso.jpg" />
                    <span id="lanceAtual"></span>
                </div>
                <div class="ladoDir">
                    <canvas id="canvas" width="180" height="180"></canvas>
                    <div class="contador">
                      <p id="num"></p>
                      <p id="texto"></p>
                    </div>
                    <button id="btnEnviar" style="display: none" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only">
                        <span class="ui-button-text">Oferecer R$ 25,00</span>
                    </button>
                    <button id="btnExtra" style="display: none" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only">
                        <span class="ui-button-text" style="width: 150px; padding: 2px 0;">Comprar Ingresso Extra</span>
                    </button>
                </div>
            </div>
            <div style="clear: both"></div>
        </div>
    </ui:define>
</ui:composition>
